package com.micro.train.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.micro.train.entity.TrainMeal;
import com.micro.train.repository.TrainMealRepository;
import com.micro.train.service.TrainMealService;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 火车餐服务实现类
 */
@Service
public class TrainMealServiceImpl extends ServiceImpl<TrainMealRepository, TrainMeal> implements TrainMealService {
    
    @Override
    public TrainMeal addMeal(TrainMeal meal) {
        this.save(meal);
        return meal;
    }
    
    @Override
    public TrainMeal updateMeal(Long mealId, TrainMeal meal) {
        TrainMeal existingMeal = getMealById(mealId);
        if (existingMeal == null) {
            throw new RuntimeException("餐品不存在，ID：" + mealId);
        }
        
        meal.setMealId(mealId);
        this.updateById(meal);
        return meal;
    }
    
    @Override
    public void deleteMeal(Long mealId) {
        TrainMeal meal = getMealById(mealId);
        if (meal == null) {
            throw new RuntimeException("餐品不存在，ID：" + mealId);
        }
        this.removeById(mealId);
    }
    
    @Override
    public List<TrainMeal> getAllMeals() {
        return this.list();
    }
    
    @Override
    public TrainMeal getMealById(Long mealId) {
        return this.getById(mealId);
    }
    
    @Override
    public List<TrainMeal> getMealsByTrainId(Long trainId) {
        QueryWrapper<TrainMeal> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("列车ID", trainId);
        return this.list(queryWrapper);
    }
    
    @Override
    public List<TrainMeal> getMealsByType(String mealType) {
        QueryWrapper<TrainMeal> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("餐品种类", mealType);
        return this.list(queryWrapper);
    }
    
    @Override
    public List<TrainMeal> getMealsByTrainIdAndType(Long trainId, String mealType) {
        QueryWrapper<TrainMeal> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("列车ID", trainId)
                   .eq("餐品种类", mealType);
        return this.list(queryWrapper);
    }
    
    @Override
    public List<TrainMeal> getAvailableMeals(Long trainId) {
        QueryWrapper<TrainMeal> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("列车ID", trainId)
                   .eq("状态", true);
        return this.list(queryWrapper);
    }
    
    @Override
    public boolean updateStock(Long mealId, Integer quantity) {
        TrainMeal meal = getMealById(mealId);
        if (meal == null) {
            throw new RuntimeException("餐品不存在，ID：" + mealId);
        }
        
        meal.setStock(meal.getStock() + quantity);
        return this.updateById(meal);
    }
}
